package com.yingjia.yingjiauniversity.json.gson;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;

import java.lang.reflect.Type;
import java.text.NumberFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <重新处理Map的反序列化， 解决转Map所有的int数据成为double>
 *
 * @author: guoxiangxun
 * @date: 16-7-7 下午9:07
 * @version: v1.0
 */
public class MapDeserializer implements JsonDeserializer<Map<String, Object>> {
    private Gson gson;

    public void setGson(Gson gson) {
        this.gson = gson;
    }

    public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Map<String, Object> m = new LinkedHashMap<String, Object>();
        JsonObject jo = json.getAsJsonObject();
        for (Map.Entry<String, JsonElement> mx : jo.entrySet()) {
            String key = mx.getKey();
            JsonElement v = mx.getValue();
            if (v.isJsonArray()) {
                m.put(key, gson.fromJson(v, List.class));
            } else if (v.isJsonPrimitive()) {
                JsonPrimitive primitive = v.getAsJsonPrimitive();
                if (primitive.isString()) {
                    m.put(key, v.getAsString());
                } else if (primitive.isNumber()) {
                    Number num = null;
                    try {
                        num = NumberFormat.getInstance().parse(v.getAsString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    m.put(key, num);
                } else if (primitive.isBoolean()) {
                    m.put(key, v.getAsBoolean());
                }
            } else if (v.isJsonObject()) {
                m.put(key, gson.fromJson(v, Map.class));
            }

        }
        return m;
    }
}
